//  
//   JKLrcScrollView.m
//   QQMusic
//  
//   Created by albert on 16/4/9.
//   Copyright (c) 2016年 albert. All rights reserved.
//  

#import "JKLrcScrollView.h"
#import "Masonry.h"
#import "JKLrcTool.h"
#import "JKLrcLineModel.h"
#import "JKLrcLineCell.h"
#import "JKLrcLabel.h"
#import "JKMusicTool.h"
#import "JKMusicModel.h"
#import <MediaPlayer/MediaPlayer.h>

@interface JKLrcScrollView () <UITableViewDataSource>
/** tableView */
@property (nonatomic, strong) UITableView *tableView;

/** 歌词的数据 */
@property (nonatomic, strong) NSArray *lrcList;

/** 当前播放的歌词的下标 */
@property (nonatomic, assign) NSInteger currentIndex;
@end

@implementation JKLrcScrollView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setupTableView];
    }
    return self;
}

//  此方法比awakeFromNib执行的早
- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self setupTableView];
    }
    return self;
}

- (void)setupTableView{
    UITableView *tableView = [[UITableView alloc] init];
    [self addSubview:tableView];
    tableView.dataSource = self;
    tableView.rowHeight = 35;
    tableView.translatesAutoresizingMaskIntoConstraints = NO;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;SEL selector = NSSelectorFromString(@"setContentInsetAdjustmentBehavior:");
    
    if ([tableView respondsToSelector:selector]) {
        
        IMP imp = [tableView methodForSelector:selector];
        void (*func)(id, SEL, NSInteger) = (void *)imp;
        func(tableView, selector, 2);
        
        // [tbView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@(2)];
    }
    
    self.tableView = tableView;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    //  添加tableView的约束
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top);
        make.bottom.equalTo(self.mas_bottom);
        make.left.equalTo(self.mas_left).offset(self.bounds.size.width);
        make.right.equalTo(self.mas_right);
        make.width.equalTo(self.mas_width);
        make.height.equalTo(self.mas_height);
    }];
    
    //  设置tableView多出的滚动区域
    self.contentSize = CGSizeMake(self.bounds.size.width * 2, 0);
    //  self.tableView.contentOffset = CGPointMake(0, -self.bounds.size.height * 0.5);
    self.tableView.contentInset = UIEdgeInsetsMake(self.bounds.size.height * 0.5, 0, self.bounds.size.height * 0.5, 0);
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.lrcList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //  创建cell
    JKLrcLineCell *cell = [JKLrcLineCell lrcLineCellWithTableView:tableView];
    
    if (self.currentIndex == indexPath.row) {
        cell.lrcLabel.font = [UIFont systemFontOfSize:20];
    }else{
        cell.lrcLabel.font = [UIFont systemFontOfSize:14];
        cell.lrcLabel.progress = 0;
    }
    
    //  取出模型
    JKLrcLineModel *lrcLine = self.lrcList[indexPath.row];
    
    cell.lrcLabel.text = lrcLine.text;
    
    return cell;
}

#pragma mark - 重写setLrcName方法
- (void)setLrcName:(NSString *)lrcName{
    //  重置保存的当前位置的下标
    self.currentIndex = 0;
    
    //  保存歌词名称
    _lrcName = [lrcName copy];
    
    //  锁屏切换歌曲后要立即改变歌曲信息
    self.currentTime = 0;
    [self setupLockScreenInfoWithLockImage:[UIImage imageNamed:[JKMusicTool playingMusic].icon]];
    
    //  解析歌词
    self.lrcList = [JKLrcTool lrcToolWithLrcName:lrcName];
    
    //  刷新表格
    [self.tableView reloadData];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
}

#pragma mark - 重写setCurrentTime方法
- (void)setCurrentTime:(NSTimeInterval)currentTime{
    _currentTime = currentTime;
    
    //  1、拿到i位置的歌词
    NSInteger count = self.lrcList.count;
    for (NSInteger i = 0; i < count; i++) {
        JKLrcLineModel *currentLrcLine = self.lrcList[i];
        
        //  2、拿到下一行的歌词
        NSInteger nextIndex = i + 1;
        JKLrcLineModel *nextLrcLine = nil;
        if (nextIndex < count) {
            nextLrcLine = self.lrcList[nextIndex];
        }
        
        //  3、用当前的时间和i位置的歌词比较，并且和下一句比较，如果大于i位置的时间，并且小于下一句歌词的时间，那么显示当前的歌词
        if (self.currentIndex != i && currentTime >= currentLrcLine.time && currentTime < nextLrcLine.time) {
            //  3.1 获取需要刷新的行号
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
            
            //  3.2 记录当前i的行号
            self.currentIndex = i;
            
            //  3.3 刷新当前的行和上一行
            [self.tableView reloadRowsAtIndexPaths:@[indexPath, previousIndexPath] withRowAnimation:(UITableViewRowAnimationNone)];
           
            //  3.4 显示对应行的歌词（滚动到对应行）
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
            
            //  3.5 设置外面歌词的label的显示歌词
            self.lrcLabel.text = currentLrcLine.text;
            
            //  3.6 生成锁屏界面的图片
            [self generateLockScreenImage];
        }
        
        //  4、根据进度，显示label画多少
        if (self.currentIndex == i) {
            //  4.1 拿到i位置的cell
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            JKLrcLineCell *cell = (JKLrcLineCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            
            //  4.2 更新label的进度
            CGFloat progress = (currentTime - currentLrcLine.time) / (nextLrcLine.time - currentLrcLine.time);
            cell.lrcLabel.progress = progress;
            
            //  4.3 设置外面歌词label的进度
            self.lrcLabel.progress = progress;
        }
    }
}

#pragma mark - 生成锁屏界面的图片
- (void)generateLockScreenImage{
    //  1、拿到当前歌曲的图片
    JKMusicModel *playingMusic = [JKMusicTool playingMusic];
    UIImage *currentImage = [UIImage imageNamed:playingMusic.icon];
    
    //  2、拿到三句歌词
    //  2.1 拿到当前的歌词
    JKLrcLineModel *currentLrcLine = self.lrcList[self.currentIndex];
    
    //  2.2 上一句歌词
    NSInteger previousIndex = self.currentIndex - 1;
    JKLrcLineModel *previousLrcLine = nil;
    if (previousIndex >= 0) {
        previousLrcLine = self.lrcList[self.currentIndex - 1];
    }
    
    //  2.3 下一句歌词
    NSInteger nextIndex = self.currentIndex + 1;
    JKLrcLineModel *nextLrcLine = nil;
    if (nextIndex < self.lrcList.count) {
        nextLrcLine = self.lrcList[nextIndex];
    }
    
    //  3、画水印图片
    //  3.1 获取上下文
    UIGraphicsBeginImageContext(currentImage.size);
    
    //  3.2 将图片画上去
    [currentImage drawInRect:(CGRectMake(0, 0, currentImage.size.width, currentImage.size.height))];
    
    //  3.3 将歌词画到图片上
    CGFloat textH = 25;
    //  设置文字居中
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentCenter;
    
    //  上一句和下一句的歌词文字属性
    NSMutableDictionary *otherTextAttr = [NSMutableDictionary dictionary];
    otherTextAttr[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    otherTextAttr[NSForegroundColorAttributeName] = [UIColor lightGrayColor];
    //  文字居中
    otherTextAttr[NSParagraphStyleAttributeName] = style;
    
    [previousLrcLine.text drawInRect:(CGRectMake(0, currentImage.size.height - 3 * textH, currentImage.size.width, textH)) withAttributes:otherTextAttr];
    [nextLrcLine.text drawInRect:(CGRectMake(0, currentImage.size.height - 1 * textH, currentImage.size.width, textH)) withAttributes:otherTextAttr];
    
    //  当前歌词的文字属性
    NSMutableDictionary *currentTextAttr = [NSMutableDictionary dictionary];
    currentTextAttr[NSFontAttributeName] = [UIFont systemFontOfSize:20];
    currentTextAttr[NSForegroundColorAttributeName] = [UIColor whiteColor];
    //  文字居中
    currentTextAttr[NSParagraphStyleAttributeName] = style;
    
    [currentLrcLine.text drawInRect:(CGRectMake(0, currentImage.size.height - 2 * textH, currentImage.size.width, textH)) withAttributes:currentTextAttr];
    
    //  4、生成带歌词水印的图片
    UIImage *lockImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //  5、设置锁屏信息
    [self setupLockScreenInfoWithLockImage:lockImage];
    
    //  6、关闭上下文
    UIGraphicsEndImageContext();
}

- (void)setupLockScreenInfoWithLockImage:(UIImage *)lockImage{
    //  1、获取当前正在播放的歌曲
    JKMusicModel *playingMusic = [JKMusicTool playingMusic];
    
    //  2、获取锁屏界面中心
    MPNowPlayingInfoCenter *playingInfoCenter = [MPNowPlayingInfoCenter defaultCenter];
    
    //  3、设置展示信息
    NSMutableDictionary *playingInfo = [NSMutableDictionary dictionary];
    //  歌曲名称
    [playingInfo setObject:playingMusic.name forKey:MPMediaItemPropertyAlbumTitle];
    //  歌手名称
    [playingInfo setObject:playingMusic.singer forKey:MPMediaItemPropertyAlbumArtist];
    
    //  锁屏图片
    MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc] initWithImage:lockImage];
    [playingInfo setObject:artWork forKey:MPMediaItemPropertyArtwork];
    
    //  总时长
    [playingInfo setObject:@(self.duration) forKey:MPMediaItemPropertyPlaybackDuration];
    //  当前播放时间
    [playingInfo setObject:@(self.currentTime) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    
    playingInfoCenter.nowPlayingInfo = playingInfo;
    
    //  4、让应用程序可以接受远程事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
@end
